<?php
require_once __DIR__ . '/../include/config.inc.php';
require_once __DIR__ . '/../include/utils.class.php';
require_once __DIR__ . '/../include/class.sosumi.php';

$loader = require __DIR__ . '/../vendor/autoload.php';
$loader->add ( 'Controller', __DIR__ . '/../src' );
$loader->add ( 'Entity', __DIR__ . '/../src' );
$loader->add ( 'User', __DIR__ . '/../src' );

$config = new \Doctrine\ORM\Configuration ();
$config->setMetadataCacheImpl ( new \Doctrine\Common\Cache\ArrayCache () );
$driverImpl = $config->newDefaultAnnotationDriver ( array (
                __DIR__ . '/../src' 
), false );
$config->setMetadataDriverImpl ( $driverImpl );

$config->setProxyDir ( __DIR__ . '/../cache/Proxies' );
$config->setProxyNamespace ( 'Proxies' );

$connectionOptions = array (
                'driver' => 'pdo_mysql',
                'host' => DB_HOST,
                'dbname' => DB_NAME,
                'user' => DB_USER,
                'password' => DB_PASS,
                'charset' => DB_CHAR 
);

$today = date ( 'Y-m-d', strtotime ( 'today' ) );

$em = \Doctrine\ORM\EntityManager::create ( $connectionOptions, $config );

$qb = $em->createQueryBuilder ();
$qb->select ( array (
                'p' 
) )->from ( '\Entity\Purchase', 'p' )->where ( 'p.status = :status' )->andWhere ( 'p.gpsType = :gpsType' )->andWhere ( 'p.wakeUpTime <= :wakeUpTime' )->setParameter ( 'status', 1 )->setParameter ( 'gpsType', 1 )->setParameter ( 'wakeUpTime', date ( 'Y-m-d H:i:s' ) );
$query = $qb->getQuery ();
$purchases = $query->getResult ();

foreach ( $purchases as $itm ) {
    try {
        $ssm = new Sosumi ( $itm->getGpsAcct (), $itm->getGpsPass () );
        $loc = $ssm->locate ();
        
        $qb = $em->createQueryBuilder ();
        $qb->select ( array (
                        'd' 
        ) )->from ( '\Entity\PurchaseDairy', 'd' )->where ( 'd.date = :date' )->andWhere ( 'd.owner = :owner' )->setParameter ( 'date', $today )->setParameter ( 'owner', $itm );
        $query = $qb->getQuery ();
        $dailies = $query->getResult ();
        if (count ( $dailies ) == 0) {
            $daily = new \Entity\PurchaseDairy ();
            $daily->setOwner ( $itm );
            $em->persist ( $daily );
            $em->flush ();
        } else {
            $daily = $dailies [0];
        }
        $daily->setTotalCheckIns ( $daily->getTotalCheckIns () + 1 );
        
        $dist = (count ( $dailies ) == 0) ? 0 : Utils::distance ( $itm->getLastLat (), $itm->getLastLng (), $loc ['latitude'], $loc ['longitude'], 'K' );
        
        $wakeUpTime = new \DateTime ( 'now' );
        if ($dist >= 0.1 || count ( $dailies ) == 0) {
            $record = new \Entity\PurchaseRecord ();
            $record->setLat ( $loc ['latitude'] );
            $record->setLng ( $loc ['longitude'] );
            $record->setDist ( $dist );
            $record->setOwner ( $itm );
            $em->persist ( $record );
            
            $itm->setLastLat ( $loc ['latitude'] );
            $itm->setLastLng ( $loc ['longitude'] );
            $itm->setLastDist ( $dist );
            
            $wakeUpTime->add ( new DateInterval ( 'PT1M' ) );
            
            $daily->setTotalRecords ( $daily->getTotalRecords () + 1 );
            $daily->setTotalDist ( $daily->getTotalDist () + $dist );
        } else {
            $wakeUpTime->add ( new DateInterval ( 'PT5M' ) );
        }
        
        $itm->setLastCheckIn ( new \DateTime ( 'now' ) );
        $itm->setWakeUpTime ( $wakeUpTime );
        
        $em->flush ();
    } catch ( Exception $ex ) {
        Utils::dump($ex->getMessage());
    }
}